package com.youaishujuhui.devops.web.dao.host;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;

import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.springframework.stereotype.Service;

import com.youaishujuhui.devops.web.domain.host.Host;
import com.youaishujuhui.devops.web.po.Select2PO;
import com.youaishujuhui.devops.web.util.Common;

@Service
public class HostDao {

	@Resource(name = "nutDao")
    private Dao nutDao;
	
	public List<String> queryProperty(String gameId) {
		Sql sql = Sqls.create("SELECT DISTINCT property FROM t_host WHERE gameId = @gameId AND state = " + Common.HOST_STATE_ONLINE);
	    sql.params().set("gameId", Integer.parseInt(gameId));
	    
	    sql.setCallback(new SqlCallback() {
	        public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
	            List<String> list = new LinkedList<String>();
	            while (rs.next()) {	            	
	                list.add(rs.getString("property"));
	            }
	            	
	            return list;
	        }
	    });
	    
	    nutDao.execute(sql);
	    return sql.getList(String.class);
	}

	public List<Select2PO> queryBestDeployHost(int gameId, String property) {
		Sql sql = Sqls.create("SELECT hostId, ctccIp AS ip, (maxGameServerCount - curGameServerCount) AS rest "
				+ "FROM t_host WHERE curGameServerCount < maxGameServerCount "
				+ "AND property = @property AND state = " + Common.HOST_STATE_ONLINE + " AND gameId = @gameId AND role = @role ORDER BY rest DESC");
	    sql.params().set("property", property);
	    sql.params().set("gameId", gameId);
	    sql.params().set("role", Common.HOST_ROLE_GAME_SERVER);
		
	    sql.setCallback(new SqlCallback() {
	        public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
	            List<Select2PO> list = new LinkedList<Select2PO>();
	            while (rs.next()) {
	            	String hostId = rs.getString("hostId");
	            	String ip = rs.getString("ip");
	            	int rest = rs.getInt("rest");
	            	Select2PO po = new Select2PO();
	            	po.setId(hostId);
	            	po.setText(ip + ":" + rest);
	                list.add(po);
	            }
	            	
	            return list;
	        }
	    });
	    
	    nutDao.execute(sql);
	    return sql.getList(Select2PO.class);
	}

	public void IncrCurGameServerCount(int hostId) {
		Host host = nutDao.fetch(Host.class, hostId);
		host.setCurGameServerCount(host.getCurGameServerCount() + 1);

		nutDao.update(host, "^curGameServerCount$");
	}

	public void updateCurGameServerCount(Host host) {
		nutDao.update(host, "^curGameServerCount$");
	}
}
